java在httpSession中存储扩展对象
在下面的代码中,learning是一个学习实例,我想将其保存为http会话的原样
learning = new Learning(learningContext);
HttpSession webSession = request.getSession();
webSession.setAttribute("learning", learning);
Learning learnTest = webSession.getAttribute("learning");
当我运行下面的代码时,我得到:
Incompatible types
Learning learnTest = webSession.getAttribute("learning")
required: Learning
found: Object
我可以将非通用对象保存到会话中吗?有没有其他方法可以做到这一点
# 1 楼答案
javadoc for
HttpSession.getAttribute
说:我的意思是,通过构造,它总是返回一个简单的对象。正如你所知道(或希望)的那样,你已经在那里放置了一个
Learning
,你只需要做一个显式转换:# 2 楼答案
你需要像这样投射物体-
您需要强制转换为特定类型,因为getAttribute的返回类型是Object